/**
 * @Description: 产品管理相关API接口
 * @Author: lujq
 * @Date: 2024-12-21
 * @LastEditors: lujq
 * @LastEditTime: 2024-12-21 16:30:00
 */

import { http } from './index'
import request from './index'
import type { Product, ApiResponse } from '@/types'

// 产品列表查询参数接口
export interface ProductListParams {
  page?: number
  size?: number
  name?: string
  category?: string
  priceRange?: string
  stockStatus?: string
  sortBy?: string
  sortOrder?: 'asc' | 'desc'
}

// 产品列表响应接口
export interface ProductListResponse {
  list: Product[]
  total: number
  page: number
  size: number
}

/**
 * 获取产品列表
 * @param {ProductListParams} params - 查询参数
 * @returns {Promise<ApiResponse<ProductListResponse>>} 产品列表响应
 */
export const getProductList = async (
  params: ProductListParams = {},
): Promise<ApiResponse<ProductListResponse>> => {
  try {
    // 构建查询URL，包含分页和过滤参数
    const queryParams = new URLSearchParams()
    
    if (params.page) queryParams.append('page', params.page.toString())
    if (params.size) queryParams.append('pageSize', params.size.toString())
    if (params.name) queryParams.append('name', params.name)
    if (params.category) queryParams.append('category', params.category)
    if (params.priceRange) queryParams.append('priceRange', params.priceRange)
    if (params.stockStatus) queryParams.append('stockStatus', params.stockStatus)
    if (params.sortBy) queryParams.append('sortBy', params.sortBy)
    if (params.sortOrder) queryParams.append('sortOrder', params.sortOrder)
    
    const response = await http.get<{
      items: Product[]
      total: number
      page: number
      pageSize: number
      totalPages: number
    }>(`/products?${queryParams.toString()}`)
    
    // 转换为前端期望的格式
    return {
      ...response,
      data: {
        list: response.data.items,
        total: response.data.total,
        page: response.data.page,
        size: response.data.pageSize
      }
    }
  } catch (error) {
    console.error('产品API调用失败:', error)
    throw error
  }
}

/**
 * 获取产品详情
 * @param {string | number} id - 产品ID
 * @returns {Promise<ApiResponse<Product>>} 产品详情响应
 */
export const getProductDetail = (id: string | number): Promise<ApiResponse<Product>> => {
  return http.get(`/products/${id}`)
}

/**
 * 创建产品
 * @param {Partial<Product>} data - 产品数据
 * @returns {Promise<ApiResponse<Product>>} 创建结果响应
 */
export const createProduct = (data: Partial<Product>): Promise<ApiResponse<Product>> => {
  return http.post('/products', data)
}

/**
 * 更新产品
 * @param {string | number} id - 产品ID
 * @param {Partial<Product>} data - 产品数据
 * @returns {Promise<ApiResponse<Product>>} 更新结果响应
 */
export const updateProduct = (
  id: string | number,
  data: Partial<Product>,
): Promise<ApiResponse<Product>> => {
  return http.put(`/products/${id}`, data)
}

/**
 * 删除产品
 * @param {string | number} id - 产品ID
 * @returns {Promise<ApiResponse<void>>} 删除结果响应
 */
export const deleteProduct = (id: string | number): Promise<ApiResponse<void>> => {
  return http.delete(`/products/${id}`)
}

/**
 * 批量删除产品
 * @param {(string | number)[]} ids - 产品ID数组
 * @returns {Promise<ApiResponse<void>>} 批量删除结果响应
 */
export const batchDeleteProducts = (ids: (string | number)[]): Promise<ApiResponse<void>> => {
  return http.delete('/products/batch', { data: { ids } })
}

/**
 * 获取热销产品列表
 * @param {number} limit - 限制数量，默认10
 * @returns {Promise<ApiResponse<Product[]>>} 热销产品列表响应
 */
export const getHotProducts = (limit: number = 10): Promise<ApiResponse<Product[]>> => {
  return http.get(`/products/hot?limit=${limit}`)
}

/**
 * 获取滞销产品列表
 * @param {number} limit - 限制数量，默认10
 * @returns {Promise<ApiResponse<Product[]>>} 滞销产品列表响应
 */
export const getSlowProducts = (limit: number = 10): Promise<ApiResponse<Product[]>> => {
  return http.get(`/products/slow?limit=${limit}`)
}

/**
 * 获取产品统计信息
 * @returns {Promise<ApiResponse<any>>} 产品统计信息响应
 */
export const getProductStats = (): Promise<ApiResponse<any>> => {
  return http.get('/products/stats')
}

/**
 * 更新产品库存
 * @param {string | number} id - 产品ID
 * @param {number} stock - 新库存数量
 * @returns {Promise<ApiResponse<void>>} 更新结果响应
 */
export const updateProductStock = (
  id: string | number,
  stock: number,
): Promise<ApiResponse<void>> => {
  return http.patch(`/products/${id}/stock`, { stock })
}

/**
 * 更新产品状态
 * @param {string | number} id - 产品ID
 * @param {string} status - 新状态
 * @returns {Promise<ApiResponse<void>>} 更新结果响应
 */
export const updateProductStatus = (
  id: string | number,
  status: string,
): Promise<ApiResponse<void>> => {
  return http.patch(`/products/${id}/status`, { status })
}

/**
 * 搜索产品
 * @param {string} keyword - 搜索关键词
 * @param {number} limit - 限制数量，默认20
 * @returns {Promise<ApiResponse<Product[]>>} 搜索结果响应
 */
export const searchProducts = (
  keyword: string,
  limit: number = 20,
): Promise<ApiResponse<Product[]>> => {
  return http.get(`/products/search?keyword=${encodeURIComponent(keyword)}&limit=${limit}`)
}

/**
 * 获取产品类别列表
 * @returns {Promise<ApiResponse<any[]>>} 产品类别列表响应
 */
export const getProductCategories = (): Promise<ApiResponse<any[]>> => {
  return http.get('/products/categories')
}

/**
 * 导入产品数据
 * @param {FormData} formData - 包含文件的表单数据
 * @returns {Promise<ApiResponse<any>>} 导入结果响应
 */
export const importProducts = (formData: FormData): Promise<ApiResponse<any>> => {
  return http.post('/products/import', formData, {
    headers: {
      'Content-Type': 'multipart/form-data',
    },
  })
}

/**
 * 导出产品数据
 * @param {ProductListParams} params - 导出参数
 * @returns {Promise<Blob>} 导出文件
 */
export const exportProducts = (params: ProductListParams = {}): Promise<Blob> => {
  return request.get('/products/export', { params, responseType: 'blob' })
}

/**
 * 获取产品销售趋势
 * @param {string | number} id - 产品ID
 * @param {string} period - 时间周期 (week/month/quarter/year)
 * @returns {Promise<ApiResponse<any[]>>} 销售趋势数据响应
 */
export const getProductSalesTrend = (
  id: string | number,
  period: string = 'month',
): Promise<ApiResponse<any[]>> => {
  return http.get(`/products/${id}/sales-trend?period=${period}`)
}

/**
 * 获取产品库存预警列表
 * @param {number} threshold - 库存预警阈值，默认100
 * @returns {Promise<ApiResponse<Product[]>>} 库存预警产品列表响应
 */
export const getStockWarningProducts = (
  threshold: number = 100,
): Promise<ApiResponse<Product[]>> => {
  return http.get(`/products/stock-warning?threshold=${threshold}`)
}

/**
 * 复制产品
 * @param {string | number} id - 源产品ID
 * @param {Partial<Product>} overrides - 覆盖的字段
 * @returns {Promise<ApiResponse<Product>>} 复制结果响应
 */
export const copyProduct = (
  id: string | number,
  overrides: Partial<Product> = {},
): Promise<ApiResponse<Product>> => {
  return http.post(`/products/${id}/copy`, overrides)
}
